package com.nengchuan.kbms.dfs.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nengchuan.kbms.common.DfsTreeNode;
import com.nengchuan.kbms.dfs.entity.dto.UserFilePageDTO;
import com.nengchuan.kbms.dfs.entity.dto.UserFileUploadDTO;
import com.nengchuan.kbms.dfs.entity.dto.UserFolderDTO;
import com.nengchuan.kbms.dfs.entity.po.UserFile;
import com.nengchuan.kbms.dfs.entity.vo.UserFileVO;
import com.nengchuan.kbms.dfs.service.UserFileService;
import com.nengchuan.kbms.dfs.service.UserFolderService;
import com.nengchuan.model.model.NcPageInfo;
import com.nengchuan.model.model.WrappedResult;
import com.nengchuan.util.MapperUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户文件（个人空间上传的文件） 前端控制器
 * </p>
 *
 * @author abe
 * @since 2020-04-02
 */
@RestController
@RequestMapping("/space")
@Api(tags = "知识库数据后台管理 > 个人空间 【已完成】")
public class SpaceController {

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private UserFolderService userFolderService;

    @PostMapping("/page")
    @ApiOperation(value = "用户文件（夹）列表")
    public WrappedResult<NcPageInfo<UserFileVO>> page(@RequestBody UserFilePageDTO pageDTO) {
        IPage<UserFileVO> pageList = userFileService.folderAndFilePage(pageDTO);
        return WrappedResult.success(MapperUtils.mappingNcPage(pageList, UserFileVO.class));
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除个人空间中的文件，文件夹，及收藏的文件，文件夹")
    public WrappedResult<Boolean> deleteFiles(@ApiParam(value = "用户文件id，多个以,分隔", required = true) @RequestParam Serializable id) {
        return WrappedResult.success(userFileService.removeFiles(id));
    }

    @PostMapping(value = "/file/upload")
    @ApiOperation(value = "文件上传")
    public WrappedResult<UserFileVO> uploadFile(
            @ApiParam(value = "用户文件夹id", required = true) @RequestParam Long userFolderId,
            @ApiParam(value = "备注，描述") @RequestParam(required = false) String remark,
            MultipartFile file) throws Exception {
        UserFileUploadDTO dto = new UserFileUploadDTO();
        dto.setUserFolderId(userFolderId);
        dto.setRemark(remark);
        dto.setFileName(file.getOriginalFilename());
        dto.setFileSize(file.getSize());
        UserFileVO userFileVO = userFileService.uploadFile(dto, file.getInputStream());
        return WrappedResult.success(userFileVO);
    }

    @GetMapping(value = "/file/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ApiOperation(value = "文件下载")
    public void downloadFile(
            @ApiParam(value = "文件id", required = true) @RequestParam Long id,
            HttpServletResponse response) {
        UserFile userFile = userFileService.getById(id);
        Objects.requireNonNull(userFile, "文件不存在");
        try {
            String fileName = URLEncoder.encode(userFile.getFileName(), "UTF-8");
            response.reset();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition" ,"attachment;filename=\"" +fileName+ "\"");
            userFileService.downloadFile(id, response.getOutputStream());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @PostMapping("/folder/save")
    @ApiOperation(value = "新增个人文件夹")
    public WrappedResult<Long> save(@RequestBody UserFolderDTO dto) {
        return WrappedResult.success(userFolderService.saveFolder(dto));
    }

    @PostMapping("/folder/update")
    @ApiOperation(value = "修改个人文件夹")
    public WrappedResult<Boolean> update(@RequestBody UserFolderDTO dto) {
        return WrappedResult.success(userFolderService.updateFolder(dto));
    }

    @PostMapping("/folder/delete")
    @ApiOperation(value = "删除个人文件夹")
    public WrappedResult<Boolean> delete(@ApiParam(value = "用户文件夹id", required = true) @RequestParam Serializable id) {
        return WrappedResult.success(userFolderService.removeFolder(id));
    }

    @GetMapping("/folder/tree")
    @ApiOperation(value = "用户文件夹树（层级结构）")
    public WrappedResult<List<DfsTreeNode>> tree(@ApiParam(value = "文件夹id") @RequestParam(required = false) Long id) {
        return WrappedResult.success(userFolderService.tree(id));
    }

}
